class ActivityAdminController < ApplicationController
  layout 'main'
  after_filter :post_log
  
  def index
    @activities = Activity.paginate :conditions =>["status=?","Y"], :per_page => 10, :page=>params[:page]
  end
  
  def new
    
  end
  
  def add_new
    activity = Activity.new(params[:activity])
    if(params[:activity][:filename]!=nil && params[:activity][:filename]!='')
      filename = Activity.save_file(params[:activity][:filename])
      activity.filename = filename
    end
    activity.user_id = session[:user_id]
    activity.status = 'Y'
    activity.save
    flash[:notice] = 'เพิ่มข่าว/บริการเป็นที่เรียบร้อยแล้ว'
    redirect_to :action => 'index'
  end
  
  def edit
    @activity = Activity.find(params[:id])
  end
  
  def update
    #get old filename
    old_filename = Activity.find(params[:activity][:id]).filename
    activity = Activity.update(params[:activity][:id], params[:activity])
    if(params[:activity][:filename]!=nil && params[:activity][:filename]!='')
      filename = Activity.save_file(params[:activity][:filename])
      activity.filename = filename
    else
      activity.filename = old_filename
    end
    if(params[:del_file]!=nil)
	activity.filename = nil
	file_name = "#{RAILS_ROOT}/public/files/"+old_filename
	File.delete(file_name) if File.exist?(file_name)
    end
    activity.save
    flash[:notice] = 'แก้ไขข่าว/บริการเป็นที่เรียบร้อยแล้ว'
    redirect_to :action => 'index'
  end
  
  def delete
    #Activity.delete(params[:id])
    Activity.update(params[:id], :status => 'D')
    flash[:notice] = 'ลบข่าว/บริการเป็นที่เรียบร้อยแล้ว'
    redirect_to :action => 'index'
  end
end
